/*!
 * Ext JS Library 3.3.1
 * Copyright(c) 2006-2010 Sencha Inc.
 * licensing@sencha.com
 * http://www.sencha.com/license
 */
// Application instance for showing user-feedback messages.
//var App = new Ext.App({});
var fm = Ext.form;
var base_url = '<?php echo base64_decode($_GET['baseUrl']);?>';
var total_row = 50;
<?php 
	$langList = unserialize(base64_decode($_GET['langList']));
	$langFilter = array();
	foreach($langList as $k=>$v){
		$langFilter[]=array($k,$v);
	}
	$langFilter = json_encode($langFilter);
	$langList = json_encode($langList);
?>
var langFilter = <?php echo $langFilter;?>;
var langList = <?php echo $langList;?>;
var proxy = new Ext.data.ScriptTagProxy({
 	api: {
        read : base_url+'admin/content_management/content_grid.html',
        create : base_url+'admin/content_management/add_content.html',
        update: base_url+'admin/content_management/add_content.html',
        destroy: base_url+'admin/content_management/delete_content.html'
    }
});
/*proxy.addListener('beforeload', function(scriptProxy,params){
	offset = params.start;
});*/
// The new DataWriter component.
var writer = new Ext.data.JsonWriter({
    encode: true   // <-- don't return encoded JSON -- causes Ext.Ajax#request to send data using jsonData config rather than HTTP params
});

// Typical Store collecting the Proxy, Reader and Writer together.
var store = new Ext.data.JsonStore({
    //id: 'id',
    //restful: true,     // <-- This Store is RESTful
	start : 'start',
	remoteSort: true,
    totalProperty: 'total',
    proxy: proxy,
    root: 'data',
    fields : [
              {name: 'id'},
              {name: 'content_name', type: 'string', allowBlank: false},
              {name: 'content_html', type: 'string'},
              {name: 'language',type: 'string'},
              {name: 'edit',type: 'string'}  
          ],
	  listeners: {
	      save: function(s, b, d) {
	    	  store.save();
	      }
	  },  
    writer: writer    // <-- plug a DataWriter into the store just as you would a Reader
});

// load the store immeditately
//store.load();

var filters = new Ext.ux.grid.GridFilters({
    // encode and local configuration options defined previously for easier reuse
    encode: true, // json encode the filter query
    local: true,   // defaults to false (remote filtering)
    filters: [{
        type: 'numeric',
        dataIndex: 'id'
    }, {
        type: 'string',
        dataIndex: 'content_name'
    }, {
        type: 'string',
        dataIndex: 'content_html',
        disabled: true
    }, {
        type: 'list',
        dataIndex: 'language',
        options: langFilter,
        phpMode: true
    }, {
        type: 'string',
        dataIndex: 'edit',
        disabled: true
    }]
});
var createColModel = function (finish, start) {

    var columns = [{header: "ID", 
                	width: 40, 
                	sortable: true,
                	sort: 'id', 
                	dataIndex: 'id'
                },{
                	header: "Name", 
                	width: 100, 
                	sortable: true, 
                	sort: 'content_name',
                	dataIndex: 'content_name', 
                	editor: new Ext.form.TextField({})
                },{
                	header: "Content", 
                	//width: 100, 
                	sortable: false, 
                	dataIndex: 'content_html', 
                	editor: new Ext.form.TextArea()
                },{
                	header: "Language",
                	renderer: formatLanguage, 
                	width: 50, 
                	sortable: true,
                	dataIndex: 'language', 
                	editor: new fm.ComboBox({
                	   editable: false,
                       typeAhead: true,
                       triggerAction: 'all',                       
                       lazyRender:true,
					   mode: 'local',
					   store: new Ext.data.ArrayStore({
					       id: 0,
					       fields: [
					           'value',
					           'displayText'
					       ],
					       data: langFilter
					   }),
					   valueField: 'value',
					   displayField: 'displayText',
					   listClass: 'x-combo-list-small'
                   })
               },{
                	header: "Edit", 
                	width: 100, 
                	sortable: true,
                	sort: 'id',
                	dataIndex: 'edit'
                }
               ];

    return new Ext.grid.ColumnModel({
        columns: columns.slice(start || 0, finish),
        defaults: {
            sortable: true
        }
    });
};

Ext.onReady(function() {
    Ext.QuickTips.init();

    // use RowEditor for editing
    var editor = new Ext.ux.grid.RowEditor({
        saveText: 'Update'
    });
    // Create a typical GridPanel with RowEditor plugin
    var contentGrid = new Ext.grid.GridPanel({
        renderTo: 'content-grid',
        iconCls: 'icon-grid',
        frame: true,        
        height: eval(Ext.getBody().getViewSize().height - 280),
        store: store,
        plugins: [editor,filters],
        colModel: createColModel(5),
        listeners: {
            render: {
                fn: function(){
                    store.load({
                        params: {
                            start: 0,
                            limit: total_row
                        }
                    });
                }
            }
        },
        tbar: [{
            text: 'Add',
            iconCls: 'silk-add',
            handler: onAdd
        }, '-', {
            text: 'Delete',
            iconCls: 'silk-delete',
            handler: onDelete
        }, '-'],
        bbar: new Ext.PagingToolbar({
            store: store,
            pageSize: total_row,
            plugins: [filters]
        }),
        viewConfig: {
            forceFit: true
        }

    });
    /**
     * onAdd
     */
    function onAdd(btn, ev) {
        var u = new contentGrid.store.recordType({});
        editor.stopEditing();
        contentGrid.store.insert(0, u);
        editor.startEditing(0);
    }
    /**
     * onDelete
     */
    function onDelete() {
        var recs = contentGrid.getSelectionModel().getSelections() ;
        if (!recs) {
            return false;
        }
        for(var i in recs)
        {
            contentGrid.store.remove(recs[i]);
        }
    }
    //store.on();

});
function formatLanguage(value){	
	if(value!='')
		return eval('langList.'+value);
	else return '';
}